<?php $this->_extends('_layouts/main_layout'); ?>
<?php $this->_block('title'); ?>
	Email Flow
<?php $this->_endblock(); ?>

<?php $this->_block('contents'); ?>
<div id="content" class="box">
	<h1><?php echo "Email Flow"; ?></h1>
	<fieldset>
    	<legend>Email Sent Events</legend>
    	<input type="button" id="events_add" value="Add Event" />
    	
    	<div id="add_event_dialog">
	     	<form id="event_edit" method="post" action="<?php echo url('emailflow/emailevents');?>">
	    		<table>
	    			<tr><th colspan="2" id="edit_title">Add Events</th></tr>
	    			<tr>
	    				<td colspan="2">
	    					Event Name:
	    					<input name="event_name" />
	    				</td>
	    			</tr>
	    			
	    			<tr>
	    				<td colspan="2">
	    					<input type="radio" name="logic" id="logic_and" value="and" checked="checked" /><label style="cursor: pointer;" for="logic_and">Meet all conditions below</label> &nbsp;&nbsp;&nbsp;&nbsp;
	    					<input type="radio" name="logic" id="logic_or" value="or" /><label style="cursor: pointer;" for="logic_or">Just Meet one condition of below</label>
	    				</td>
	    			</tr>
	    			
	    			<tr>
	    				<td colspan="2" id="send_template_block">
	    					Send Template:
	    					<?php if(!empty($existsTemplates)): foreach($existsTemplates as $k => $existsTemplate): ?>
	    						<input type="radio" name="send_template" id="<?php echo 'send_template'.$existsTemplate['id']; ?>" value="<?php echo $existsTemplate['id']; ?>" <?php echo $k == 0 ? 'checked="checked"' : '' ?> />
								<label for="<?php echo 'send_template'.$existsTemplate['id']; ?>" id="<?php echo 'send_template_name'.$existsTemplate['id']; ?>" style="cursor: pointer;"><?php echo $existsTemplate['template_name']; ?></label>
			            	<?php endforeach; endif; ?>
	    				</td>
	    			</tr>
	    			
	    			<tr class="conditions" id="condition_orig">
	    				<td>
	    					<select name='condition'>
	    						<option value='age'>Age</option>
	    						<option value='gender'>Gender</option>
	    						<option value='livetime'>Register to now</option>
	    						<option value='won'>Won</option>
	    						<option value='balance'>Balance</option>
	    						<option value='credit'>Credit</option>
	    						<option value='offer'>Offer</option>
	    						<option value='inactive'>Inactive</option>
	    						<option value='site'>Site</option>
	    					</select>
	    					<select name='relation'>
	    						<option value="&lt;">&lt;</option>
	    						<option value="&lt;=">&lt;=</option>
	    						<option value="=">=</option>
	    						<option value="&gt;">&gt;</option>
	    						<option value="&gt;=">&gt;=</option>
	    					</select>
	    					<input name="condition_val" />
	    				</td>
	    				<td>
	    					<input type='button' value='+' class='addcondition' />
	    					<input type='button' value='-' class='removecontion' />
	    				</td>
	    			</tr>
	    			
	    			<tr>
	    				<td colspan="2">
	    					<input type="submit" id="emailEventsSub" name="Add" value="Save" />
	    					<span id="warning_text" class="warning_text" style="color: #F00;"></span>
	    				</td>
	    			</tr>
	    		</table>
	    	</form>
    	</div>
    	
    	<table style="text-align: center;">
         	<tbody>
             	<tr>
             		<th>Event Name</th>
             		<th>Logic</th>
             		<th>Template Name</th>
             		<th>Conditions</th>
             		<th>Active</th>
             	</tr>
             	
             	<tr class="event_disp"></tr>
             	<?php if(!empty($existsEvents)): foreach($existsEvents as $k => $existsEvent): ?>
             		<tr class="event_disp" id="<?php echo 'event_' . $k; ?>">
                    	<td class="event_modify" style="cursor: pointer; color: #33F;"><?php echo $existsEvent['event_name'] ?></td>
                    	<td class="event_logic"><?php echo $existsEvent['logic'] ?></td>
                    	<td class="event_template_name"><?php echo $existsEvent['template_name'] ?></td>
                    	<td class="event_conditions" style="width: 50%;"><?php echo $existsEvent['conditionsStr'] ?></td>
                    	<td><input type="checkbox" name="actived" <?php echo $existsEvent['actived'] == 1? 'checked=true' : ''; ?> /></td>
                	</tr>
            	<?php endforeach; endif; ?>
            	
            	<tr style="text-align: right;">
            		<td colspan="0"><input type="button" id="event_implement" value="Save" /></td>
            	</tr>
        	</tbody>
     	</table>
     	<script>
			$('#event_implement').click(function(){
				var activeArr = {};
				$.each($('.event_disp'), function(k, v){
					var id = $(v).attr('id');
					var actived = $(v).find('[name="actived"]').attr('checked');
					activeArr[id] = actived;
				});
			
				$.ajax({
					type: 'POST',
					url: '<?php echo url('emailflow/emaileventsactived');?>',
					data: {activeArr: activeArr},
					success: function(data){
						//alert('active stat saved!');
					}
				});
			});
			
			
			$('.addcondition').live('click', function(){
				$('.conditions:last').after($('#condition_orig').clone().attr('id', ''));
				$('.conditions:last [name="condition"]').val($('#condition_orig [name="condition"]').val());
			});
			
			$('.conditions[id!="condition_orig"] .removecontion').live('click', function(){
				$(this).parent().parent().remove();
			});
			
			$('[name="condition"]').live('change', function(){
				switch($(this).val()){
					case 'gender':
						$(this).parent().find('[name="relation"]').html("<option>=<\/option>");
						$(this).parent().find('[name="condition_val"]').replaceWith("<select name='condition_val'><option value='2'>All</option><option value='1'>Male</option><option value='0'>Female</option></select>");
						break;
					case 'site':
						$(this).parent().find('[name="relation"]').html("<option>=<\/option>");
						$(this).parent().find('[name="condition_val"]').replaceWith('<?php
								 echo Util::buildDropDownList(
										 	array('name'=>'condition_val'),
										 	$sites,
										 	false,
										 	array('k'=>'', 'l'=>'--All--')
										 );
									?>');
						break;
					default:
						$(this).parent().find('[name="relation"]').html("<option value='&lt;'>&lt;</option><option value='&lt;='>&lt;=</option><option value='='>=</option><option value='&gt;'>&gt;</option><option value='&gt;='>&gt;=</option>");
						$(this).parent().find('[name="condition_val"]').replaceWith("<input name='condition_val' /><span style='color:#F00;'></span>");
				}
			});
			
			$('#emailEventsSub[name="Add"]').live('click', function(){
				var condition = new Array();
				var relation = new Array();
				var condition_val = new Array();
			
				$.each($('.conditions'), function(k ,v){
					condition.push($(v).find('[name="condition"]').val());
					relation.push($(v).find('[name="relation"]').val());
					condition_val.push($(v).find('[name="condition_val"]').val());
				});

				var template_id = $('[name="send_template"]:checked').val();
			
				$.ajax({
					type: 'POST',
					url: '<?php echo url('emailflow/emailevents');?>',
					data: {
						event_name: $('[name="event_name"]').val(),
						logic: $('[name="logic"]:checked').val(),
						condition: condition,
						relation: relation,
						condition_val: condition_val,
						template_id: template_id
					},
					success: function(data){
						if(data){
							$('#warning_text').html('Added');
							$('.event_disp:last').after("<tr class='event_disp' id='event_"+data['event_id']+"'><td class='event_modify' style='cursor: pointer; color: #33F;'>"+data['event_name']+"</td><td class='event_logic'>"+data['logic']+"</td><td class='event_template_name'>"+$('#send_template_name'+data['template_id']).html()+"</td><td class='event_conditions' style='width: 50%;'>"+data['conditionsStr']+"</td><td><input type='checkbox' checked='true' /></td></tr>");

							$('#add_event_dialog').dialog('close');
						}
					},
					dataType: 'json'
				});
			
				return false;
			});
			
			$('#emailEventsSub[name="Edit"]').live('click', function(){
				var modify_id = $(this).data('modify_id');
				var condition = new Array();
				var relation = new Array();
				var condition_val = new Array();
			
				$.each($('.conditions'), function(k ,v){
					condition.push($(v).find('[name="condition"]').val());
					relation.push($(v).find('[name="relation"]').val());
					condition_val.push($(v).find('[name="condition_val"]').val());
				});

				var template_id = $('[name="send_template"]:checked').val();
				var event_name = $('[name="event_name"]').val();
				var logic = $('[name="logic"]:checked').val();
			
				$.ajax({
					type: 'POST',
					url: '<?php echo url('emailflow/emaileventsmodify');?>',
					data: {
						modify_id: modify_id,
						event_name: event_name,
						logic: logic,
						condition: condition,
						relation: relation,
						condition_val: condition_val,
						template_id: template_id
					},
					success: function(data){
						if(data){
							$('#warning_text').html('Saved');
							$('.event_disp#event_'+modify_id+' .event_modify').html(data['event_name']);
							$('.event_disp#event_'+modify_id+' .event_logic').html(data['logic']);
							$('.event_disp#event_'+modify_id+' .event_template_name').html($('#send_template_name'+data['template_id']).html());
							$('.event_disp#event_'+modify_id+' .event_conditions').html(data['conditionsStr']);
						}
					},
					dataType: 'json'
				});
			
				return false;
			});
			
			$('#events_add').click(function(){
				$('#event_edit').attr('action', '<?php echo url('emailflow/emailevents');?>');
				$('#event_edit #edit_title').html('Add Events');
				$('#event_edit [name="logic"]').removeAttr('checked');
				$('#event_edit [name="logic"][value="and"]').attr('checked', 'checked');
				$('#event_edit [name="event_name"]').val('');
				$('#event_edit .conditions[id!="condition_orig"]').remove();
				$('#event_edit .conditions [name="condition"]').val('');
				$('#event_edit .conditions [name="relation"]').html("<option value='&lt;'>&lt;</option><option value='&lt;='>&lt;=</option><option value='='>=</option><option value='&gt;'>&gt;</option><option value='&gt;='>&gt;=</option>");
				$('#event_edit .conditions [name="condition_val"]').replaceWith('<input name="condition_val" />');
				$('#emailEventsSub').attr('name', 'Add');
				$('[name="delete_event_btn"]').remove();
				$('#warning_text').html('');
				$('#add_event_dialog').dialog('open');
			});
			
			$('.event_modify').live('click', function(){
				$('#warning_text').html('');
				var event_id = $(this).parent().attr('id').replace('event_', '');
				$.ajax({
					type: 'GET',
					url: '<?php echo url('emailflow/emaileventinfo'); ?>',
					data: {
						event_id: event_id
					},
					success: function(eventInfo){
						if(eventInfo){
							$('#event_edit').attr('action', '<?php echo url('emailflow/emaileventsmodify');?>');
							$('#event_edit #edit_title').html('Edit Event - [' + eventInfo['event_name'] + ']');
			
							$('#event_edit [name="event_name"]').val(eventInfo['event_name']);
							
							$('#event_edit [name="logic"]').removeAttr('checked');
							$('#event_edit [name="logic"][value="'+eventInfo['logic']+'"]').attr('checked', 'checked');
			
							$('#event_edit .conditions[id!="condition_orig"]').remove();
							$('#emailEventsSub').attr('name', 'Edit').data('modify_id', event_id);
							if($('[name="delete_event_btn"]').size() <= 0){
								$('#emailEventsSub').after('<input type="button" name="delete_event_btn" value="Delete" />');
							}
							$.each(eventInfo['conditions'], function(k, condition){
								if(k > 0){
									$('#event_edit .conditions:last').after($('#condition_orig').clone().attr('id', ''));
								}
								if(condition['factor'] == 'gender'){
									$('#event_edit .conditions:last [name="condition_val"]').replaceWith("<select name='condition_val'><option value='2'>All</option><option value='1'>Male</option><option value='0'>Female</option></select>");
									$('#event_edit .conditions:last [name="relation"]').html("<option>=<\/option>");
								}else if(condition['factor'] == 'site'){
									$('#event_edit .conditions:last [name="condition_val"]').replaceWith('<?php
											 echo Util::buildDropDownList(
													 	array('name'=>'condition_val'),
													 	$sites,
													 	false,
													 	array('k'=>'', 'l'=>'--All--')
													 );?>'
									);
									$('#event_edit .conditions:last [name="relation"]').html("<option>=<\/option>");
								}else{
									$('#event_edit .conditions:last [name="condition_val"]').replaceWith('<input name="condition_val" />');
									$('#event_edit .conditions:last [name="relation"]').html("<option value='&lt;'>&lt;</option><option value='&lt;='>&lt;=</option><option value='='>=</option><option value='&gt;'>&gt;</option><option value='&gt;='>&gt;=</option>");
								}
								$('#event_edit .conditions:last [name="condition"]').val(condition['factor']);
								$('#event_edit .conditions:last [name="condition_val"]').val(condition['val']);
								$('#event_edit .conditions:last [name="relation"]').val(condition['relation']);

								$('#add_event_dialog').dialog('open');
							});
							$('[name="send_template"]').removeAttr('checked');
							$('#send_template'+eventInfo['template_id']).attr('checked', 'checked');
						}
					},
					dataType: 'json'
				});
			});

			$('[name="delete_event_btn"]').live('click', function(){
				var event_id = $('#emailEventsSub').data('modify_id');
				$.ajax({
					type: 'POST',
					url: '<?php echo url('emailflow/emaileventdelete'); ?>',
					data: {
						event_id: event_id
					},
					success: function(del){
						if(del){
							$('#event_'+event_id).remove();
							$('#add_event_dialog').dialog('close');
						}else{
							$('#warning_text').html('Error occured');
						}
					},
					dataType: 'json'
				});
			});

			$('#add_event_dialog').dialog({
				autoOpen: false,
				height: 'auto',
				width: 'auto',
				modal: true,
				open: function(){
					$('.warning_text').html('');
				},
				buttons: {Cancel: function(){
								$(this).dialog( "close" );
							  }
						 }
			});
		</script>
    </fieldset>
    
    
    <fieldset>
    	<legend>Email Flow Template</legend>
    	<link rel="stylesheet" href="<?php echo CSS_DIR; ?>kindeditor/themes/default/default.css" />
		<link rel="stylesheet" href="<?php echo CSS_DIR; ?>kindeditor/plugins/code/prettify.css" />
		<script charset="utf-8" src="<?php echo JS_DIR; ?>kindeditor/kindeditor.js"></script>
		<script charset="utf-8" src="<?php echo JS_DIR; ?>kindeditor/lang/en.js"></script>
		<script charset="utf-8" src="<?php echo JS_DIR; ?>kindeditor/plugins/code/prettify.js"></script>
		<script>
			var editor;
			KindEditor.ready(function(K) {
				editor = K.create('#templateEdit', {
					width: '800px'
				});
			});
		</script>
		
		
		
		
		<input type="button" id="template_add" value="Add Template" />
		<table id="add_template_dialog">
			<tr>
				<th id="template_edit_title" colspan="2">
					Template Content - Add
				</th>
			</tr>
			<tr>
				<th>Template Name</th>
				<td><input type="text" name="template_name" size="60" /></td>
			</tr>
			<tr>
				<th>Subject</th>
				<td><input type="text" name="template_subject" size="60" /></td>
			</tr>
			<tr>
				<td colspan="2">
					<textarea id="templateEdit" style="width:700px;height:200px;visibility:hidden;">
						<?php echo htmlspecialchars($templateContents); ?>
					</textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="button" id="templateSubmit" name="Add" value="Save" />
					<span id="tmpwarning_text" class="warning_text" style="color: #F00;"></span>
				</td>
			</tr>
		</table>
		
		<table>
			<tr>
				<th colspan="0">Exist Templates</th>
			</tr>
			<tr id="exist_template_list">
				<?php foreach($existsTemplates as $k => $existsTemplate): ?>
					<td style="cursor: pointer; color: #33F;" class="template_modify" id="<?php echo 'template_modify'.$existsTemplate['id'] ?>"><?php echo $existsTemplate['template_name']; ?></td>
				<?php endforeach; ?>
			</tr>
		</table>
		<span id="tmpwarning_text2" class="warning_text" style="color: #F00;"></span>
		
		
		
		<script>
			$('#template_add').click(function(){
				$('#template_edit_title').html('Template Content - Add');
				$('[name="template_name"]').val('');
				$('[name="template_subject"]').val('');
				$('[name="template_condition"]').removeAttr('checked');
				$('#tmpwarning_text').html('');
				editor.html('');
				$('#templateSubmit').attr('name', 'Add');
				$('[name="delete_temp_btn"]').remove();
				$('#test_send_block').remove();
				$('#add_template_dialog').dialog('open');
			});

			$('#templateSubmit[name="Add"]').live('click', function(){
				var template_name = $('[name="template_name"]').val();
				var template_subject = $('[name="template_subject"]').val();
				var content = editor.html();
				$.ajax({
					type: 'POST',
					url: '<?php echo url('emailflow/addtemplate');?>',
					data: {
						template_name: template_name,
						template_subject: template_subject,
						template_content: content
					},
					success: function(insert_id){
						if(insert_id){
							$('#tmpwarning_text').html('Added');
							$('#exist_template_list').append("<td id='template_modify"+insert_id+"' class='template_modify' style='cursor: pointer; color: #33F;'>"+template_name+"</td>");

							$('#send_template_block').append('<input type="radio" name="send_template" id="send_template'+insert_id+'" value="'+insert_id+'" /><label for="send_template'+insert_id+'" id="send_template_name'+insert_id+'" style="cursor: pointer;">'+template_name+'</label>');
							$('#add_template_dialog').dialog('close');
						}else{
							$('#tmpwarning_text').html('Error occured');
						}
					},
					dataType: 'json'
				});
			});

			$('.template_modify').live('click', function(){
				var template_id = $(this).attr('id').replace('template_modify', '');
				$.ajax({
					type: 'GET',
					url: '<?php echo url('emailflow/emailtemplateinfo');?>',
					data: {
						template_id: template_id
					},
					success: function(template_info){
						if(template_info){
							$('#template_edit_title').html('Template Content - '+'['+template_info['template_name']+']');
							$('[name="template_name"]').val(template_info['template_name']);
							$('[name="template_subject"]').val(template_info['template_subject']);
							editor.html(template_info['content']);
							$('#templateSubmit').data('template_id', template_id).attr('name', 'Edit');
							if($('[name="delete_temp_btn"]').size() <= 0){
								$('#templateSubmit').after('<input type="button" name="delete_temp_btn" value="Delete" />');
							}
							if($('#test_send_block').size() <= 0){
								$('#templateSubmit').parent().parent().after('<tr id="test_send_block"><th>Test Sendto</th><td><input type="text" name="template_test_sendto" size="50" /><input type="button" id="template_testsend" value="Send" /></td></tr>');
							}
							$('#add_template_dialog').dialog('open');
						}
					},
					dataType: 'json'
				});
			});

			$('#template_testsend').live('click', function(){
				var sendto = $('[name="template_test_sendto"]').val();
				var template_id = $('#templateSubmit').data('template_id');
				$.ajax({
					type: 'POST',
					url: '<?php echo url('emailflow/testsend'); ?>',
					data: {
						sendto: sendto,
						template_id: template_id
					},
					success: function(send){
						if(send){
							$('#tmpwarning_text').html('has sent');
						}
					},
					dataType: 'json'
				});
			});

			$('[name="delete_temp_btn"]').live('click', function(){
				var template_id = $('#templateSubmit').data('template_id');
				$.ajax({
					type: 'POST',
					url: '<?php echo url('emailflow/emailtemplatedelete'); ?>',
					data: {
						template_id: template_id
					},
					success: function(del){
						if(del){
							$('#send_template'+template_id).remove();
							$('#send_template_name'+template_id).remove();
							$('#template_modify'+template_id).remove();
							$('#tmpwarning_text2').html('Template has been deleted, events which use this template have no tamplate now. Check and reset! ');
							$('#add_template_dialog').dialog('close');
						}else{
							$('#tmpwarning_text').html('Error occured');
						}
					},
					dataType: 'json'
				});
			});


			$('#templateSubmit[name="Edit"]').live('click', function(){
				var template_id = $(this).data('template_id');
				var template_name = $('[name="template_name"]').val();
				var template_subject = $('[name="template_subject"]').val();
				var content = editor.html();
				$.ajax({
					type: 'POST',
					url: '<?php echo url('emailflow/emailtemplatemodify');?>',
					data: {
						template_id: template_id,
						template_name: template_name,
						template_subject: template_subject,
						template_content: content
					},
					success: function(data){
						if(data){
							$('#tmpwarning_text').html('Saved');
							$('.template_modify#template_modify'+template_id).html(template_name);

							$('#send_template_name'+template_id).html(template_name);
						}else{
							$('#tmpwarning_text').html('Error occured');
						}
					},
					dataType: 'json'
				});
			});

			$('#add_template_dialog').dialog({
				autoOpen: false,
				height: 'auto',
				width: 'auto',
				modal: true,
				open: function(){
					$('.warning_text').html('');
				},
				buttons: {Cancel: function(){
								$(this).dialog( "close" );
							  }
						 }
			});
		</script>
    </fieldset>
    
    
</div>


<?php $this->_endblock(); ?>